// --------------------------------------------打卡页面-----------------------------------------------
import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import styles from "../style/clock.module.css";
import left from "../img/left.png";
import color from "../img/clock.png";
import { task } from "../api/task";

// 定义类型接口
interface ClockDay {
  status: boolean;
  score: number;
  index: number;
  date: string;
}

interface Task {
  title: string;
  desc: string;
  score: number;
  id?: number;
}

interface ApiResponse {
  code: number;
  data: {
    week: ClockDay[];
    list: Task[];
    count?: number;
  };
  msg?: string;
}

function ClockPage() {
  const navigate = useNavigate(); // 正确引入 navigate
  const [tasks, setTasks] = useState<Task[]>([]);
  const [clockDays, setClockDays] = useState<ClockDay[]>([]);
  const [reminderOn, setReminderOn] = useState(true);
  const [continuousDays, setContinuousDays] = useState(0);
  const user = JSON.parse(localStorage.getItem("user") || "null");

  useEffect(() => {
    fetchClockData();
  }, []);
  //============ 打卡页面接口数据===================
  const fetchClockData = async () => {
    try {
      const response = await task(
        { uid: user.data.id }, // 第一个参数：data
        { token: user.data.token, uid: user.data.id } // 第二个参数：headers
      );

      console.log("API响应数据:", response.data);

      // 根据响应码处理数据
      if (response.data.code === 1) {
        console.log("API请求成功");
        processData(response.data.data);
      }
    } catch (error) {
      console.error("请求失败:", error);
    }
  };
  const processData = (data: ApiResponse["data"]) => {
    setClockDays(data.week);
    setTasks(data.list);

    // 计算连续打卡天数
    const days = data.week.filter((d) => d.status).length;
    setContinuousDays(days);
  };

  const renderClockDays = () => {
    return clockDays.map((day: ClockDay, index) => (
      <div key={`${day.date}-${index}`} className={styles.already}>
        {day.status ? (
          <>
            <img src="../img/clocked.png" alt="已打卡" />
            <span>{day.index}天</span>
          </>
        ) : (
          <>
            <div className={styles.score}>+{day.score}</div>
            <span>{day.index}天</span>
          </>
        )}
      </div>
    ));
  };

  const renderTasks = () => {
    if (tasks.length === 0) {
      return (
        <div className={styles.task}>
          <div className={styles.task_area}>暂无任务...</div>
        </div>
      );
    }

    return tasks.map((task) => (
      <div key={task.title} className={styles.task}>
        <div className={styles.task_area}>
          <div className={styles.task_left}>
            <div className={styles.task_top}>
              <span id={styles.task_name}>{task.title}</span>
              <span id={styles.task_score}>+{task.score}</span>
            </div>
            <div className={styles.task_bottom}>{task.desc}</div>
          </div>
          <div className={styles.task_right}>
            <button className={styles.go_clock}>去打卡</button>
          </div>
        </div>
      </div>
    ));
  };
  return (
    <div className={styles.container}>
      {/* 顶部导航 */}
      <div className={styles.top}>
        <div className={styles.top_img}>
          <img src={left} onClick={() => navigate(-1)} alt="返回" />
        </div>
        <div className={styles.top_text}>打卡任务</div>
      </div>
      {/* 主图部分 */}
      <div className={styles.main}>
        <img src={color} alt="打卡主题" />
        <div className={styles.text}>
          不是看到了希望才坚持
          <div className={styles.part}>而是坚持才会看到希望</div>
        </div>
      </div>

      {/* 打卡区域 */}
      <div className={styles.clock}>
        <div className={styles.clock_top}>
          <div className={styles.left_day}>
            已连续打卡
            <span id={styles.day}>{continuousDays}</span>天
          </div>
          <div className={styles.remind}>
            <span>打卡提醒</span>
            <div className={styles.switch_container}>
              <input
                type="checkbox"
                id="switch"
                checked={reminderOn}
                onChange={(e) => setReminderOn(e.target.checked)}
              />
              <label htmlFor="switch" className={styles.switch_label} />
            </div>
          </div>
        </div>
        <div className={styles.week}>{renderClockDays()}</div>
      </div>
      {/* 今日任务 */}
      <div className={styles.today}>今日任务</div>
      {/* 任务详情 */}
      {renderTasks()}
    </div>
  );
}

export default ClockPage;
